<?php

namespace app\mobile\controller;

use app\common\model\Cart;
use think\Lang;

class Membercart extends MobileMember {

    public function _initialize() {
        parent::_initialize();
        Lang::load(APP_PATH . 'mobile\lang\zh-cn\membercart.lang.php');
    }


    protected function getDeliveryTypeByCartId($cart_id) {
        $cart = Cart::get($cart_id);
        $goods = \app\common\model\Goods::get($cart['goods_id']);
        return $goods['trade_mode'];
    }
    /**
     * 购物车列表
     */
    public function cart_list() {
        $model_cart = model('cart');

        $condition = array('buyer_id' => $this->member_info['member_id']);
        $cart_list = $model_cart->getCartList('only_db', $condition);

        # 购物车连接有没有对应的商品id
        $goods_ids = $this->request->param('goods_ids', '', 'trim');
        if ($goods_ids) {
            $goods_ids = explode(',', $goods_ids);
            if (is_array($goods_ids)) {
                # 获得商品数据，判断商品id在不在购物车里面，如果不在购物车里面就新增
                $need_add_goods = array_diff($goods_ids, array_column($cart_list, 'goods_id'));
                if ($need_add_goods) {
                    # 循环执行添加购物车
                    foreach ($need_add_goods as $item) {
                        $this->cart_add($item, 1, true);
                    }
                }
            }
        }
        # 添加完购物车后再进行查询一次
        $cart_list = $model_cart->getCartList('db', $condition);

        // 购物车列表 [得到最新商品属性及促销信息]
        $cart_list = model('buy_1','logic')->getGoodsCartList($cart_list);
        $model_goods = model('goods');

        $model_config = model('config');
//        $order_amount_limit = $model_config->getOneConfigByCode('order_amount_limit');
        $order_internal_amount_limit = $model_config->getOneConfigByCode('order_internal_amount_limit');
        $order_bonded_amount_limit = $model_config->getOneConfigByCode('order_bonded_amount_limit');
        $order_external_amount_limit = $model_config->getOneConfigByCode('order_external_amount_limit');

        $group = [];
        $sum = 0;
        $cart_a = array();
        $cart_a[0] = [];
        $k=0;
        foreach ($cart_list as $key => $val) {
            $goods_data = $model_goods->getGoodsOnlineInfoForShare($val['goods_id']);//goods

            if (!$goods_data) continue;

            $cart_a[0]['goods'][$key] = $goods_data;

            $cart_a[0]['goods'][$key]['cart_id'] = $val['cart_id'];
            $cart_a[0]['goods'][$key]['goods_num'] = $val['goods_num'];
            $cart_a[0]['goods'][$key]['goods_image_url'] = goods_cthumb($val['goods_image'], 0);

            if (isset($goods_data['goods_spec'])&&$goods_data['goods_spec'] == 'N;') {
                $cart_a[0]['goods'][$key]['goods_spec'] = '';
            }
            if ($goods_data['goods_promotion_type'] > 0) {
                $cart_a[0]['goods'][$key]['goods_price'] = $goods_data['goods_promotion_price'];
            }
            $cart_a[0]['goods'][$key]['gift_list'] = isset($val['gift_list'])?$val['gift_list']:'';

//            $cart_a[0]['order_amount_limit'] = $order_amount_limit['value'];
            $cart_a[0]['order_internal_amount_limit'] = $order_internal_amount_limit['value'];
            $cart_a[0]['order_bonded_amount_limit'] = $order_bonded_amount_limit['value'];
            $cart_a[0]['order_external_amount_limit'] = $order_external_amount_limit['value'];
            $cart_list[$key]['goods_sum'] = sc_price_format($val['goods_price'] * $val['goods_num']);
            $sum += $cart_list[$key]['goods_sum'];
            $k++;
        }

        // 产品根据类型分组
        $trade_group = [];
        $goods_type = ["1"=>"普通商品","2"=>"保税货物"];
        if(isset($cart_a[0]['goods']) &&  $cart_a[0]['goods'])

            foreach ($cart_a[0]['goods'] as $item) {

                isset($trade_group[$item['goods_type']]) or $trade_group[$item['goods_type']] = [
                    'valid' => 1, // 暂时不做有效性验证
                    'goods' => [],
                    'trade_mode' => $item['goods_type'],
                    'trade_mode_format' => $goods_type[$item['goods_type']],
                    'total_amount' => 0,
                    'total' => 0,
                ];
                $trade_group[$item['goods_type']]['goods'][] = $item;
                $trade_group[$item['goods_type']]['total_amount'] += $item['goods_price'] * $item['goods_num'];
                $trade_group[$item['goods_type']]['total'] += $item['goods_num'];
            }

            // foreach ($cart_a[0]['goods'] as $item) {
            //
            //     isset($trade_group[$item['trade_mode']]) or $trade_group[$item['trade_mode']] = [
            //         'valid' => 1, // 暂时不做有效性验证
            //         'goods' => [],
            //         'trade_mode' => $item['trade_mode'],
            //         'trade_mode_format' => config('trade_mode.'.$item['trade_mode']),
            //         'total_amount' => 0,
            //         'total' => 0,
            //     ];
            //     $trade_group[$item['trade_mode']]['goods'][] = $item;
            //     $trade_group[$item['trade_mode']]['total_amount'] += $item['goods_price'] * $item['goods_num'];
            //     $trade_group[$item['trade_mode']]['total'] += $item['goods_num'];
            // }

        if(isset($cart_l)){
            $cart_b=array_values($cart_l);
        }else{
            $cart_b=array();
        }

        output_data(array(
            'cart_list' => $trade_group,
            'trade_mode_config' => $goods_type,
//            'order_amount_limit' => config('order_amount_limit'),
            'order_internal_amount_limit' => config('order_internal_amount_limit'),
            'order_bonded_amount_limit' => config('order_bonded_amount_limit'),
            'order_external_amount_limit' => config('order_external_amount_limit'),
            'order_quantity_limit' => config('order_quantity_limit'),
            'sum' => sc_price_format($sum),
            'cart_count' => count($cart_list),
            'cart_val'=>$cart_b
        ));
    }

    /**
     * 购物车添加
     * @param int goods_id 商品id
     * @param int quantity 商品数量
     */
    public function cart_add($goods_id = '', $quantity = 1, $call_of_this = false) {
        if(!$this->member_info['is_buylimit']){
            output_error('您没有商品购买的权限,如有疑问请联系客服人员');
        }
        $goods_id = $goods_id ?: intval(input('post.goods_id'));
        $quantity = $quantity ?: intval(input('post.quantity'));
        if ($goods_id <= 0 || $quantity <= 0) {
            output_error('参数错误');
        }

        $model_goods = model('goods');
        $model_cart = model('cart');
        $logic_buy_1 = model('buy_1','logic');

        $goods_info = $model_goods->getGoodsOnlineInfoAndPromotionById($goods_id);

        $goods_cart = $model_cart->getCartInfo(array('goods_id'=>$goods_id));

        //验证是否可以购买
        if (empty($goods_info)) {
            output_error('商品已下架或不存在');
        }

        //抢购
        $logic_buy_1->getGroupbuyInfo($goods_info, $quantity);

        //限时折扣
        $logic_buy_1->getXianshiInfo($goods_info, $quantity);

        if (intval($goods_info['goods_storage']) < 1 || intval($goods_info['goods_storage']) < $quantity) {
            output_error('库存不足');
        }

        $param = array();
        $param['buyer_id'] = $this->member_info['member_id'];
        $param['store_id'] = $goods_info['store_id'];
        $param['goods_id'] = $goods_info['goods_id'];
        $param['goods_name'] = $goods_info['goods_name'];
        $param['goods_price'] = $goods_info['goods_price'];
        $param['goods_image'] = $goods_info['goods_image'];

        if ($call_of_this == true) {
            # 本类其他方法直接调用添加购物车时
            try {
                $model_cart->addCart($param, 'db', $quantity);
            } catch (\Exception $e) {
                return false;
            }
            return true;
        }

        try {
            $result = $model_cart->addCart($param, 'db', $quantity);
        } catch (\Exception $e) {
            output_error($e->getMessage());
        }

        if ($result) {
            output_data('1');
        } else {
            output_error('加入购物车失败');
        }
    }

    /**
     * 购物车删除
     */
    public function cart_del() {
        $cart_id = intval(input('post.cart_id'));

        $model_cart = model('cart');

        if ($cart_id > 0) {
            $condition = array();
            $condition['buyer_id'] = $this->member_info['member_id'];
            $condition['cart_id'] = $cart_id;

            $model_cart->delCart('db', $condition);
        }

        output_data('1');
    }

    /**
     * 更新购物车购买数量
     */
    public function cart_edit_quantity() {
        $cart_id = intval(abs(input('post.cart_id')));
        $quantity = intval(abs(input('post.quantity')));
        if (empty($cart_id) || empty($quantity)) {
            output_error('参数错误');
        }

        $model_cart = model('cart');

        $cart_info = $model_cart->getCartInfo(array('cart_id' => $cart_id, 'buyer_id' => $this->member_info['member_id']));

        $model_goods = model('goods');
        $goods_info = $model_goods->getGoodsOnlineInfoAndPromotionById($cart_info['goods_id']);
        $goods_cart = $model_cart->getCartInfo(array('goods_id'=>$cart_info['goods_id']));


        $goods_max_limit = intval($goods_info['goods_max_limit']);
        $goods_min_limit = intval($goods_info['goods_min_limit']);

        if( $goods_max_limit >0){
            if ($goods_max_limit < $quantity) {
                output_error('产品单笔订单最大限购 '.$goods_max_limit.' 件');
            }
        }
        if( $goods_min_limit >1){
            if ($goods_min_limit > $quantity) {
                output_error('产品单笔订单最小限购 '.$goods_min_limit.' 件');
            }
        }

        //检查是否为本人购物车
        if ($cart_info['buyer_id'] != $this->member_info['member_id']) {
            output_error('参数错误');
        }

        //检查库存是否充足
        if (!$this->_check_goods_storage($cart_info, $quantity, $this->member_info['member_id'])) {
            output_error('超出限购数或库存不足');
        }

        $data = array();
        $data['goods_num'] = $quantity;


        $where['cart_id']= $cart_id;
        $where['buyer_id']=$cart_info['buyer_id'];

        $update = $model_cart->editCart($data, $where);
        if ($update) {
            $return = array();
            $return['quantity'] = $quantity;
            $return['goods_price'] = sc_price_format($cart_info['goods_price']);
            $return['total_price'] = sc_price_format($cart_info['goods_price'] * $quantity);
            output_data($return);
        } else {
            output_error('修改失败');
        }
    }

    /**
     * 检查库存是否充足
     */
    private function _check_goods_storage(& $cart_info, $quantity, $member_id) {
        $model_goods = model('goods');
        $model_bl = model('pbundling');
        $logic_buy_1 = model('buy_1','logic');

        if ($cart_info['bl_id'] == '0') {
            //普通商品
            $goods_info = $model_goods->getGoodsOnlineInfoAndPromotionById($cart_info['goods_id']);

            //团购
            $logic_buy_1->getGroupbuyInfo($goods_info, $quantity);
            if (isset($goods_info['ifgroupbuy'])) {
                if ($goods_info['upper_limit'] && $quantity > $goods_info['upper_limit']) {
                    return false;
                }
            }

            //限时折扣
            $logic_buy_1->getXianshiInfo($goods_info, $quantity);
            if (intval($goods_info['goods_storage']) < $quantity) {
                return false;
            }
            $goods_info['cart_id'] = $cart_info['cart_id'];
            $goods_info['buyer_id'] = $cart_info['buyer_id'];
            $cart_info = $goods_info;
        } else {
            //优惠套装商品
            $bl_goods_list = $model_bl->getBundlingGoodsList(array('bl_id' => $cart_info['bl_id']));
            $goods_id_array = array();
            foreach ($bl_goods_list as $goods) {
                $goods_id_array[] = $goods['goods_id'];
            }
            $bl_goods_list = $model_goods->getGoodsOnlineListAndPromotionByIdArray($goods_id_array);

            //如果有商品库存不足，更新购买数量到目前最大库存
            foreach ($bl_goods_list as $goods_info) {
                if (intval($goods_info['goods_storage']) < $quantity) {
                    return false;
                }
            }
        }
        return true;
    }

    /**
     * 检查购物车数量
     */
    public function cart_count() {
        $model_cart = model('cart');
        $count = $model_cart->getCartCountByMemberId($this->member_info['member_id']);
        $data['cart_count'] = $count;
        output_data($data);
    }


    public function cart_batchadd (){
        output_data(1);
    }

}

?>
